import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: Routz
 * @since: 2020/10/9 22:58
 */
public class ZooOgConnect {
    private final static String CONNECTION_URL = "192.168.3.100:2181";
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String [] args) throws IOException, InterruptedException, KeeperException {
        // 创建ZK Watcher
        ZooKeeper zooKeeper = new ZooKeeper(CONNECTION_URL, 5000, watchedEvent -> {
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
                countDownLatch.countDown();
                System.out.println("---after countDown " + watchedEvent.getState());
            }
        });
        System.out.println(zooKeeper);
        System.out.println("---init " + zooKeeper.getState());
        // 确定连接后再操作
        countDownLatch.await();
        // 操作
        System.out.println("---after await" + zooKeeper.getState());

        // 创建 持久节点
        zooKeeper.create("/jnode1", "jnode1data".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        Stat stat = new Stat();
        byte[] data = zooKeeper.getData("/jnode1", true, stat);
        System.out.println(new String(data, StandardCharsets.UTF_8));
        System.out.println(stat);


    }
}
